import React, { useEffect, useRef, useState } from 'react';
import {
  Space,
  Input,
  Button,
  Table,
  TableColumnProps,
  Modal,
  Form,
  Radio,
  Select,
  Message,
  Cascader,
  Popconfirm,
} from '@arco-design/web-react';
import { IconPlus } from '@arco-design/web-react/icon';
import {
  addSysAccountApi,
  delSysAccountApi,
  getDicValueApi,
  getSysAccountApi,
  getTreeApi,
  updateSysAccountApi,
} from '@/request/api';
import login from '@/pages/login';
import { useSelector } from 'react-redux';
import { DictionaryState } from '@/store/dictionary';
const FormItem = Form.Item;
const Option = Select.Option;

const formItemLayout = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 17,
  },
};
function TeacherManagement() {
  const columns: TableColumnProps[] = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      width: 60,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '工号',
      dataIndex: 'jobNumber',
      align: 'center',
    },
    {
      title: '专业',
      dataIndex: 'dept',
      ellipsis: true,
      align: 'center',
      width: 300,
      render: (_, record) => (
        <Space size={'mini'}>
          {record.deptList.map((item) => {
            return <div key={item.id}>{item.name}</div>;
          })}
        </Space>
      ),
    },
    {
      title: '添加人',
      dataIndex: 'createByUser.name',
      align: 'center',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'op',
      align: 'center',
      render: (_, record) => (
        <Space size={'mini'}>
          <Button
            size={'mini'}
            type="outline"
            onClick={() => editStudentClick(record)}
          >
            修改
          </Button>
          <Popconfirm
            focusLock
            title="删除"
            content="确定删除?"
            onOk={() => {
              delStudentClick(record.id);
            }}
          >
            <Button size={'mini'} status={'danger'} type="outline">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [inputNameValue, setInputNameValue] = useState('');
  const [inputNumberValue, setInputNumberValue] = useState('');
  const [page, setPage] = useState({
    pageNum: 1,
    pageSize: 10,
  });

  const [student, setStudents] = useState({
    list: [],
    total: 0,
  });

  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const formRef = useRef();
  const [form] = Form.useForm();
  // formStatus:true修改,false增加
  const [updateId, setUpdateId] = useState();
  const [formData, setFormData] = useState({ deptId: [] });
  const [dept, setDept] = useState([]);
  const [stuGrade, setStuGrade] = useState([]);
  const [stuClass, setStuClass] = useState([]);

  useEffect(() => {
    fetchGradeAndClass();
  }, []);

  useEffect(() => {
    fetchTeachers();
  }, [JSON.stringify(page), inputNameValue, inputNumberValue]);

  const fetchTeachers = () => {
    getSysAccountApi({
      ...page,
      sysRoleId: 2,
      name: inputNameValue,
      number: inputNumberValue,
    })
      .then((res) => {
        const { data } = res;
        // student.list.push(...data.list);
        // student.total = data.total;
        setStudents(data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const fetchGradeAndClass = async () => {
    try {
      const dept = await getTreeApi();
      const gradeRes = await getDicValueApi({ code: 'stu_grade' });
      const classRes = await getDicValueApi({ code: 'stu_class' });
      setDept(dept.data);
      setStuGrade(gradeRes.data);
      setStuClass(classRes.data);
    } catch (e) {}
  };

  const editStudentClick = async (record) => {
    const {
      id,
      name,
      jobNumber,
      phone,
      disabled,
      remarks,
      stuGrade,
      stuClass,
      deptIds,
    } = record;
    const deptId = [];
    // 根据deptIds,获取父id
    if (deptIds.length > 0) {
      for (const item of dept) {
        for (const major of item.children) {
          if (deptIds.indexOf(major.id) !== -1) {
            deptId.push([item.id, major.id]);
          }
        }
      }
    }
    form.setFieldsValue({
      name,
      jobNumber,
      number: '',
      phone,
      disabled,
      remarks,
      stuGrade,
      stuClass,
      deptId: deptId,
    });
    setUpdateId(id);
    setVisible(true);
  };

  const delStudentClick = (id) => {
    delSysAccountApi({ id: id })
      .then((res) => {
        console.log(res);
        Message.success(res.msg);
        fetchTeachers();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const addStudentClick = async () => {
    setUpdateId(null);
    form.resetFields();
    setVisible(true);
  };

  const onOk = () => {
    const deptIds = [];
    formData.deptId.map((item) => {
      item[1] ? deptIds.push(item[1]) : null;
    });
    const info = {
      id: updateId,
      name: '',
      jobNumber: '',
      number: '',
      phone: '',
      disabled: 0,
      remarks: '',
      stuGrade: null,
      stuClass: null,
      ...formData,
      sysRoleId: 2,
      deptIds: deptIds,
    };

    if (!updateId) {
      addSysAccountApi(info)
        .then((res) => {
          setConfirmLoading(true);
          Message.success(res.msg);
          setVisible(false);
          fetchTeachers();
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          setConfirmLoading(false);
        });
    } else {
      updateSysAccountApi(info)
        .then((res) => {
          setConfirmLoading(true);
          Message.success(res.msg);
          setVisible(false);
          fetchTeachers();
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          setConfirmLoading(false);
        });
    }
  };

  const onPaginationChange = (pageNumber, pageSize) => {
    setPage({
      pageNum: pageNumber,
      pageSize: pageSize,
    });
  };

  const onValuesChange = (changeValue, values) => {
    setFormData(values);
  };

  return (
    <div>
      <Space size={24}>
        <Input.Search
          style={{
            marginBottom: 8,
            marginTop: 8,
          }}
          allowClear
          placeholder={'请输入老师姓名进行搜索'}
          onChange={(value, e) => setInputNameValue(value)}
        />
        <Input.Search
          style={{
            marginBottom: 8,
            marginTop: 8,
          }}
          allowClear
          placeholder={'请输入老师工号进行搜索'}
          onChange={(value, e) => setInputNumberValue(value)}
        />
        <Button
          type="primary"
          size={'small'}
          icon={<IconPlus />}
          onClick={() => addStudentClick()}
        >
          添加老师
        </Button>
        {/*<Button type="primary" size={'small'} icon={<IconPlus />}>*/}
        {/*  批量导入*/}
        {/*</Button>*/}
      </Space>
      <Table
        columns={columns}
        data={student.list}
        pagination={{
          total: student.total,
          showTotal: true,
          showJumper: true,
          sizeCanChange: true,
          current: page.pageNum,
          onChange: (pageNumber, pageSize) =>
            onPaginationChange(pageNumber, pageSize),
        }}
        pagePosition={'bottomCenter'}
      />
      <Modal
        title={'老师信息'}
        visible={visible}
        onOk={onOk}
        onCancel={() => setVisible(false)}
        confirmLoading={confirmLoading}
        autoFocus={false}
        focusLock={true}
      >
        <Form
          form={form}
          ref={formRef}
          autoComplete="off"
          {...formItemLayout}
          initialValues={{
            disabled: 0,
          }}
          onValuesChange={onValuesChange}
          scrollToFirstError
        >
          <FormItem
            label="姓名"
            field="name"
            rules={[{ required: true, message: '姓名是必填项' }]}
          >
            <Input placeholder="请输入姓名" />
          </FormItem>
          <FormItem
            label="工号"
            field="jobNumber"
            rules={[{ required: true, message: '学号是必填项' }]}
          >
            <Input type={'number'} placeholder="请输入学号" />
          </FormItem>
          <FormItem
            label="联系方式"
            field="phone"
            normalize={(value) => {
              if (value) {
                const val = value.replace(/[^0-9]/gi, '');
                return `${val}`;
              }
              return value;
            }}
          >
            <Input placeholder="请输入联系方式" />
          </FormItem>
          <FormItem label="状态" field="disabled">
            <Radio.Group>
              <Radio value={0}>启用</Radio>
              <Radio value={1}>禁用</Radio>
            </Radio.Group>
          </FormItem>
          <FormItem label="年级" field="stuGrade">
            <Select placeholder="请选择年级" style={{ flex: 1 }} allowClear>
              {stuGrade.map((item, index) => (
                <Option value={item.key} key={item.key}>
                  {item.value}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label="班级" field="stuClass">
            <Select placeholder="请选择班级" style={{ flex: 1 }} allowClear>
              {stuClass.map((item, index) => (
                <Option value={item.key} key={item.key}>
                  {item.value}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label="专业" field="deptId">
            <Cascader
              mode={'multiple'}
              placeholder="请选择"
              options={dept}
              fieldNames={{
                children: 'children',
                label: 'name',
                value: 'id',
              }}
            />
          </FormItem>
          <FormItem label="备注" field="remarks">
            <Input />
          </FormItem>
        </Form>
      </Modal>
    </div>
  );
}

export default TeacherManagement;
